<?php

	/**
    * @framework : My Framework
    *
    * @author: cuongnc.it659@gmail.com - Nguyễn Chí Cường - fatangel26@gmail.com - Nguyễn Bảo Trung.
    *
    */

	class helper_captcha
	{

		var $font       = 'assets/fonts/REFSAN.ttf';
		var $image_path = 'assets/captcha/';

		function make_string($length)
		{
			/* list all possible characters, similar looking characters and vowels have been removed */
			$possible = '123456789abcdfghjkmnpqrstvwxyzABCDEFGHIKLMNOPQRSTJVXYZ';
			$code = '';
			$i = 0;
			while ($i < $length)
			{
				$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
				$i ++;
			}

			return $code;
		}

		function make_captcha($width = '410', $height = '28', $characters = '6')
		{

			list($usec, $sec) = explode(" ", microtime());
			$now = ((float)$usec + (float)$sec);

			/*DELETE OLD IMAGES*/
			$current_dir = @opendir($this->image_path);

			while ($filename = @readdir($current_dir))
			{
				if ($filename != "." and $filename != ".." and $filename != "index.html")
				{
					$name = str_replace(".jpg", "", $filename);

					if (($name + 3200) < $now)
					{
						@unlink($this->image_path.$filename);
					}
				}
			}

			@closedir($current_dir);

			/*MAKE RANDOM CODE*/
			$code      = $this->make_string($characters);
			$font_size = $height * 0.45;

			if (function_exists('imagecreatetruecolor'))
			{
				$image = imagecreatetruecolor($width, $height);
			}
			else
			{
				$image = imagecreate($width, $height);
			}

			$background_color = imagecolorallocate($image, 255, 255, 255);
			$text_color       = imagecolorallocate($image, 123, 170, 27);
			$border_color     = imagecolorallocate($image, 255, 255, 255);
			$grid_color       = imagecolorallocate($image, 255, 255, 255);
			$shadow_color     = imagecolorallocate($image, 255, 255, 255);

			ImageFilledRectangle($image, 0, 0, $width, $height, $background_color);

			for( $i=0; $i < ($width*$height)/150; $i ++ )
			{
				imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $grid_color);
			}

			$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
			$x = ($width - $textbox[4])/2;
			$y = ($height - $textbox[5])/2;
			imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');

			$image_name = $now.'.jpg';
			ImageJPEG($image, $this->image_path.$image_name);

			$im = $this->image_path.$image_name;

			imagedestroy($image);

			return array('word' => $code, 'image' => $im);
		}

	}

 	/* End of file helper_captcha.php */
    /* Location: .//D/root/my_framework/helpers/helper_captcha.php */